<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios' // 假设你已经安装了axios

// 导入 Element Plus 图标
import { Edit, Check, Close } from '@element-plus/icons-vue'

const doctorInfo = ref({
  id: null,
  name: '',
  phone: '',
  hospitalId: null,
  hospitalName: '',
  level: '',
  doctorIntroduction: '',
  experienceYears: null,
  specialties: '',
  password: '' // 用于修改密码的字段
})

// 用于保存原始数据，以便在取消修改时恢复
const originalDoctorInfo = ref({})

// 是否处于编辑模式
const isEditing = ref(false)

// 获取医生ID (这里假设医生ID存储在localStorage中，实际项目中可能从登录接口获取并存储)
// ⚠️ 注意：这里最好从登录成功后后端返回的用户信息中获取，而不是简单地从 localStorage 取名为 'doctorId' 的字段
const doctorId = ref(localStorage.getItem('userId') || localStorage.getItem('doctorId') || 1) // 优先尝试userId，再是doctorId，最后硬编码

// 获取医生详情
const fetchDoctorInfo = async () => {
  if (!doctorId.value) {
    ElMessage.error('无法获取医生ID，请尝试重新登录。')
    return
  }
  try {
    const response = await axios.get(`http://localhost:8080/doctor/${doctorId.value}`)
    if (response.data.code === 200) {
      // 过滤掉不需要展示或修改的字段，例如created, updated, deleted
      // eslint-disable-next-line no-unused-vars
      const { created, updated, deleted, ...dataToDisplay } = response.data.data;
      doctorInfo.value = { ...dataToDisplay, password: '' }; // 不显示原始密码，清空密码字段
      originalDoctorInfo.value = { ...doctorInfo.value }; // 保存原始数据
      ElMessage.success('医生信息获取成功！')
    } else {
      ElMessage.error(`获取医生信息失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('获取医生信息时发生错误:', error)
    ElMessage.error('获取医生信息失败，请检查网络或服务器。')
  }
}

// 切换编辑模式
const toggleEdit = () => {
  isEditing.value = !isEditing.value
  if (!isEditing.value) {
    // 如果退出编辑模式，恢复原始数据
    doctorInfo.value = { ...originalDoctorInfo.value }
    // 清空密码字段，避免取消后再次进入编辑模式时显示上次输入但未保存的密码
    doctorInfo.value.password = '';
  }
}

// 保存修改
const saveDoctorInfo = async () => {
  // 可以在这里添加一些前端验证
  if (!doctorInfo.value.name || !doctorInfo.value.phone || !doctorInfo.value.level) {
    ElMessage.warning('姓名、电话、级别为必填项。');
    return;
  }

  try {
    const payload = {
      id: doctorInfo.value.id,
      name: doctorInfo.value.name,
      phone: doctorInfo.value.phone,
      hospitalId: doctorInfo.value.hospitalId,
      level: doctorInfo.value.level,
      doctorIntroduction: doctorInfo.value.doctorIntroduction,
      experienceYears: doctorInfo.value.experienceYears,
      specialties: doctorInfo.value.specialties,
    }

    // 只有当密码字段不为空时才发送密码
    if (doctorInfo.value.password) {
      payload.password = doctorInfo.value.password
    }

    const response = await axios.put('http://localhost:8080/doctor/update', payload)
    if (response.data.code === 200) {
      ElMessage.success('医生信息更新成功！')
      isEditing.value = false // 退出编辑模式
      fetchDoctorInfo() // 重新获取最新数据以确保数据一致性
    } else {
      ElMessage.error(`更新医生信息失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('更新医生信息时发生错误:', error)
    ElMessage.error('更新医生信息失败，请检查网络或服务器。')
  }
}

onMounted(() => {
  fetchDoctorInfo()
})
</script>

<template>
  <div class="profile-page">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">医生个人中心</span>
          <div class="actions">
            <el-button v-if="!isEditing" type="primary" :icon="Edit" @click="toggleEdit">编辑</el-button>
            <template v-else>
              <el-button type="success" :icon="Check" @click="saveDoctorInfo">保存</el-button>
              <el-button :icon="Close" @click="toggleEdit">取消</el-button>
            </template>
          </div>
        </div>
      </template>

      <el-form :model="doctorInfo" label-width="120px" class="profile-form" :disabled="!isEditing">
        <el-form-item label="医生姓名" class="form-item-display">
          <span v-if="!isEditing">{{ doctorInfo.name || 'N/A' }}</span>
          <el-input v-else v-model="doctorInfo.name"></el-input>
        </el-form-item>

        <el-form-item label="联系电话">
          <el-input v-model="doctorInfo.phone"></el-input>
        </el-form-item>

        <el-form-item label="所属医院" class="form-item-display">
          <span>{{ doctorInfo.hospitalName || 'N/A' }}</span>
        </el-form-item>

        <el-form-item label="医生级别">
          <el-input v-model="doctorInfo.level"></el-input>
        </el-form-item>

        <el-form-item label="执业年限">
          <el-input-number v-model="doctorInfo.experienceYears" :min="0" :max="50" controls-position="right"></el-input-number>
        </el-form-item>

        <el-form-item label="擅长领域">
          <el-input v-model="doctorInfo.specialties" type="textarea" :rows="2" placeholder="请填写您擅长的领域，如：心血管内科，神经外科"></el-input>
        </el-form-item>

        <el-form-item label="医生介绍">
          <el-input type="textarea" v-model="doctorInfo.doctorIntroduction" :rows="4" placeholder="请详细介绍您的专业背景、经验和专长"></el-input>
        </el-form-item>

        <el-form-item label="修改密码">
          <el-input type="password" v-model="doctorInfo.password" placeholder="留空则不修改密码" show-password></el-input>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.profile-page {
  padding: 30px; /* 增大页面内边距 */
  background-color: #f8fbfd; /* 轻微的页面背景色 */
  min-height: calc(100vh - 60px); /* 适应布局高度 */
  display: flex;
  justify-content: center;
  align-items: flex-start; /* 顶部对齐 */
}

.profile-card {
  width: 100%;
  max-width: 900px; /* 适当增大卡片最大宽度 */
  border-radius: 12px; /* 圆角更大 */
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08); /* 柔和的阴影 */
  animation: fade-in 0.5s ease-out; /* 卡片进入动画 */
}

@keyframes fade-in {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px; /* 增加底部内边距 */
  border-bottom: 1px solid #ebeef5; /* 增加分隔线 */
  margin-bottom: 20px; /* 增加与表单的间距 */
}

.card-title {
  font-size: 24px; /* 标题字号更大 */
  font-weight: bold;
  color: #333;
}

.actions .el-button {
  margin-left: 10px; /* 按钮间距 */
  border-radius: 6px; /* 按钮圆角 */
}

.profile-form {
  padding: 0 20px; /* 表单左右内边距 */
}

.el-form-item {
  margin-bottom: 25px; /* 增大表单项间距 */
  display: flex; /* 确保label和内容对齐 */
  align-items: center; /* 垂直居中对齐 */
}

/* 针对非编辑模式下的展示文本样式 */
.profile-form .form-item-display span {
  font-weight: 500;
  color: #555;
  font-size: 15px;
  min-height: 32px; /* 保持与 input 相似的高度 */
  line-height: 32px; /* 垂直居中 */
  padding-left: 10px; /* 与 input 的内边距对齐 */
  box-sizing: border-box;
  width: 100%; /* 确保占据完整宽度 */
}

/* 输入框和文本域样式 */
.el-input,
.el-textarea,
.el-input-number {
  width: 100%; /* 确保宽度填满 */
  max-width: 400px; /* 限制输入框最大宽度，避免过长 */
}

.el-input-number {
  min-width: 150px; /* 数字输入框最小宽度 */
}

/* 当表单禁用时，调整输入框背景色，使其看起来更自然 */
.el-form.is-disabled .el-input__wrapper,
.el-form.is-disabled .el-textarea__inner,
.el-form.is-disabled .el-input-number__decrease,
.el-form.is-disabled .el-input-number__increase {
  background-color: #f5f7fa; /* 稍微深一点的背景色 */
  box-shadow: none; /* 移除阴影 */
  cursor: not-allowed;
}

.el-form.is-disabled .el-input__inner,
.el-form.is-disabled .el-textarea__inner {
  color: #606266; /* 禁用状态下的文字颜色 */
  -webkit-text-fill-color: #606266; /* 兼容Safari */
}
</style>